package org.example;

import org.example.pojo.Classes;
import org.example.pojo.Student;
import org.example.util.SessionFactoryUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: HAPPY
 * @Project_name: hibernate
 * @Package_name: org.example
 * @Date: 2021/10/11 19:53
 * explain:
 */
public class MyTest01 {

    @Test
    public void test01() {
        Session session = SessionFactoryUtil.currentSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Classes classes = new Classes();
            classes.setName("一班");

            // 先保存班级
            session.save(classes);

            Student student01 = new Student("张三", "男", 14);
            Student student02 = new Student("李四", "女", 35);
            Student student03 = new Student("王五", "男", 26);
            student01.setClasses(classes);
            student02.setClasses(classes);
            student03.setClasses(classes);

//            session.save(student01);
//            session.save(student02);
//            session.save(student03);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (transaction != null) {
                transaction.rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    @Test
    public void test02() {
        Session session = SessionFactoryUtil.currentSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            Student student04 = new Student("小刚", "男", 16);
            session.save(student04);

            Student student05 = new Student("小花", "女", 26);
            session.save(student05);

            Student student06 = new Student("小红", "女", 18);
            session.save(student06);

            Classes classes = new Classes();
            classes.setName("二班");

            Set<Student> studentSet = new HashSet<>();
            studentSet.add(student04);
            studentSet.add(student05);
            studentSet.add(student06);
            classes.setStudentSet(studentSet);
            session.save(classes);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (transaction != null) {
                transaction.rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
}
